package com.zsx.shopping.user.aop;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsx.shopping.common.exception.NoPermissionException;
import com.zsx.shopping.common.session.UserVO;
import com.zsx.shopping.user.annotation.ReceiveAddressPermissionCheck;
import com.zsx.shopping.user.entity.ReceiveAddress;
import com.zsx.shopping.user.interceptor.LoginInterceptor;
import com.zsx.shopping.user.mapper.ReceiveAddressMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Aspect
@Component
public class ReceiveAddressPermissionCheckAop {

    @Resource
    private ReceiveAddressMapper receiveAddressMapper;

    @Before("@annotation(receiveAddressPermissionCheck)")
    void receiveAddressAuthorityCheck(JoinPoint point, ReceiveAddressPermissionCheck receiveAddressPermissionCheck) {
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        LocalVariableTableParameterNameDiscoverer localVariableTable = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNameArr = localVariableTable.getParameterNames(method);
        if (paramNameArr != null) {
            Object[] args = point.getArgs();
            String idParamName = receiveAddressPermissionCheck.id();
            UserVO userVO = LoginInterceptor.loginUser.get();
            LambdaQueryWrapper<ReceiveAddress> queryWrapper = new LambdaQueryWrapper<ReceiveAddress>().select(ReceiveAddress::getUserId);
            for (int i = 0; i < paramNameArr.length; i++) {
                if (paramNameArr[i].equals(idParamName)) {
                    queryWrapper.eq(ReceiveAddress::getId, args[i]);
                }
            }
            ReceiveAddress receiveAddress = receiveAddressMapper.selectOne(queryWrapper);
            if (receiveAddress == null || !userVO.getId().equals(receiveAddress.getUserId())) {
                throw new NoPermissionException();
            }
        }
    }
}
